package com.dcivision.workflow.applet;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.color.ColorSpace;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ComponentColorModel;
import java.io.ObjectInputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Locale;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.RepaintManager;
import javax.swing.UIManager;

import org.jgraph.JGraph;

import com.dcivision.workflow.applet.net.HttpOperation;

public class WindowUtilities {

  public static final String REVISION = "$Revision: 1.12 $";


  /** Tell system to use native look and feel, as in previous
   *  releases. Metal (Java) LAF is the default otherwise.
   */

  public static void setNativeLookAndFeel() {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting native LAF: " + e);
    }
  }

  public static void setJavaLookAndFeel() {
    try {
      UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting Java LAF: " + e);
    }
  }

   public static void setMotifLookAndFeel() {
    try {
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
    } catch(Exception e) {
      System.out.println("Error setting Motif LAF: " + e);
    }
  }

  /** A simplified way to see a JPanel or other Container.
   *  Pops up a JFrame with specified Container as the content pane.
   */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title,
                                    Color bgColor) {
    JFrame frame = new JFrame(title);
    frame.setBackground(bgColor);
    content.setBackground(bgColor);
    frame.setSize(width, height);
    frame.setContentPane(content);
    frame.setVisible(true);
    return(frame);
  }

  /** Uses Color.white as the background color. */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title) {
    return(openInJFrame(content, width, height, title, Color.white));
  }

  /** Uses Color.white as the background color, and the
   *  name of the Container's class as the JFrame title.
   */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height) {
    return(openInJFrame(content, width, height,
                        content.getClass().getName(),
                        Color.white));
  }
  
  public static void setListItemByID(JComboBox jComboBox,String index){
    int size = jComboBox.getItemCount();
    for(int i=0;i<size;i++){
        ListObject item = (ListObject)jComboBox.getItemAt(i);
        if(item.getID().equals(index)){
          jComboBox.setSelectedIndex(i);
          break;
        }
    }
     
  }
  
  public static void setListItemByIDs(JList jList,String[] indexArr){
    int size = jList.getModel().getSize();
    if(indexArr==null){
      return;   
    }
    int[] selectIndex = new int[indexArr.length];
    for(int i=0;i<selectIndex.length;i++){
      selectIndex[i] = -1; 
    }
    
    for(int i=0;i<size;i++){
        ListObject item = (ListObject)jList.getModel().getElementAt(i);
        for(int j=0;j<indexArr.length;j++){
          if(indexArr[j].equals(item.getID())){
            selectIndex[j] = i;
            break;
          }         
        }
    }
    jList.setSelectedIndices(selectIndex);
     
  }
  
  /**
   * splitString
   *
   * Returns string array which after spliting the input string.
   *
   * @param   src   String which going to be splitted.
   * @param   div   Delimitator for split.
   * @return        String array after split.
   */
  public static String[] splitString(String src, String div) {
    String[] result = null;
    java.util.Vector temp = new java.util.Vector();
    int idx1 = 0;
    int idx2 = 0;

    if (src == null || src.length() == 0 || div == null || div.length() == 0) {
      return(null);
    }

    try {
      while (idx2 >= 0 && idx1 < src.length()) {
        idx2 = src.indexOf(div, idx1);
        if (idx2 >= 0) {
          temp.addElement(src.substring(idx1, idx2));
        } else {
          temp.addElement(src.substring(idx1));
        }
        idx1 = idx2 + div.length();
      }

      result = new String[temp.size()];
      for (int i = 0; i < temp.size(); i++) {
        result[i] = (String)temp.elementAt(i);
      }

      return(result);
    } catch (Exception e) {
      e.printStackTrace();
      return(null);
    }
  }
  
  /**
   * getCurrentDateStr
   *
   * Returns current time in String .
   *
   * @return  String which representing the current time.
   */
  public static String getCurrentDateStr() {
    java.util.Calendar tmp = java.util.Calendar.getInstance();
    tmp.clear(java.util.Calendar.MILLISECOND);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    return simpleDateFormat.format(tmp.getTime());
  }
  
  /**
   * isNumber
   *
   * judge whether a string is a number or not 
   *
   * @return  boolean.
   */
  public static boolean isNumber(String str) {
    try {            
      Float.parseFloat(str);
  } catch (Exception e) {
      return false;
  }
  return true;
  }
  
  /**
   * isNumber
   *
   * judge whether a string is a number or not 
   *
   * @return  boolean.
   */
  public static boolean isDate(String str) {
    try {
      SimpleDateFormat df = null;
      if(str.length()>10){
        df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.US);
      } else {
        df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
      }
      df.parse(str);
	  } catch (Exception e) {
	    return false;
	  }
	  return true;
	}
  /**
   * replaceString
   *
   * Returns string after replacing the original string to the target string, no matter
   * the ori string wrapped by space or charater.
   *
   * @param   src Source string which going to be replaced
   * @param   ori Original string in the source string
   * @param   tar Target string which replaces the original string
   * @return      String after replacement taken place.
   */
  public static String replaceString(String src, String ori, String tar) {
    String result = null;

    if (src!=null && ori!=null && tar!=null){
      try {
        StringBuffer source = new StringBuffer(src);
        int appearedIndex = 0;
        int oriLength = ori.length();
        int tarLength = tar.length();
        int byPassingIndex = 0;
        // If you got exception here, please check your JDK version. JDK 1.4 is needed for this method.
        while (source.indexOf(ori,byPassingIndex)!=-1) {
          appearedIndex = source.indexOf(ori,byPassingIndex);
          if (ori.equals(source.substring(appearedIndex,appearedIndex+oriLength))) {
            source = source.replace(appearedIndex,appearedIndex+oriLength,tar);
            byPassingIndex = appearedIndex+tarLength;
          } else {
            byPassingIndex = appearedIndex;
          }
        }
        result = source.toString();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return result;
  }
  
  public static void setUIFont (javax.swing.plaf.FontUIResource f){
    //
    // sets the default font for all Swing components.
    // ex. 
    //  setUIFont (new javax.swing.plaf.FontUIResource("Serif",Font.ITALIC,12));
    //
    java.util.Enumeration keys = UIManager.getDefaults().keys();
    while (keys.hasMoreElements()) {
      Object key = keys.nextElement();
      Object value = UIManager.get (key);
      if (value instanceof javax.swing.plaf.FontUIResource)
        UIManager.put (key, f);
    }
  }
  
  /**
   * getResouceByCode
   *
   * Returns resource by key id and arg id
   * 
   *
   * @param   httpOperation HttpOperation
   * @param   hostURL string
   * @param   codeArr index -- 0:key id , index -- 1:arg1 id
   * @return      resource.
   */
  public static String getResouceByCode(HttpOperation httpOperation, String hostURL,int[] codeArr){
    ObjectInputStream inputFromServlet = null;
    String resource=null;      
    try{
      String url = "/workflow/appletMiddleware?dataType=GET_RESOURCEBYCODE";
      url+="&CODE="+AppletResource.messageCodeArr[codeArr[0]]+"&ARG1="+URLEncoder.encode(AppletResource.lableArr[codeArr[1]],"UTF-8");
      inputFromServlet = httpOperation.getObjectInputStreamFromServlet(url);
      
      if(inputFromServlet == null){
        return null;  
      }      
      Object obj = null;
      obj = inputFromServlet.readObject();
      if (obj instanceof String) {
        resource = (String) obj;
      } else if (obj instanceof Exception) {
        //otherwise type cast it to Exception and throw that exception.
        throw (Exception) obj;
      }  
    }catch(Exception e){
      e.printStackTrace();
    }
    return resource;
  }
  
  public static Object getObjectFromServlet(HttpOperation httpOperation, String url){
    ObjectInputStream inputFromServlet = null;
    String resource=null;
    Object obj=null;
    try{
      inputFromServlet = httpOperation.getObjectInputStreamFromServlet(url);     
      if(inputFromServlet == null){
        return null;  
      }      
      obj = inputFromServlet.readObject(); 
    }catch(Exception e){
      e.printStackTrace();
      //throw e;
    }
    return obj;
  }
  
  public static boolean getChartByXml(HttpOperation httpOperation, String workflowRecordID){
    return true;
  }
  
  public static BufferedImage expToImage(JGraph jgraph, int i) {
    Object aobj[] = jgraph.getRoots();
    if(aobj.length > 0)
    {
        Rectangle2D rectangle2d = jgraph.getCellBounds(aobj);
        jgraph.toScreen(rectangle2d);
        ColorSpace colorspace = ColorSpace.getInstance(1000);
        ComponentColorModel componentcolormodel = new ComponentColorModel(colorspace, false, true, 1, 0);
        BufferedImage bufferedimage = new BufferedImage((int)rectangle2d.getWidth() + 2 * i, (int)rectangle2d.getHeight() + 2 * i, 2);
        Graphics2D graphics2d = bufferedimage.createGraphics();
        if(jgraph.isOpaque())
        {
            graphics2d.setColor(jgraph.getBackground());
            graphics2d.fillRect(0, 0, bufferedimage.getWidth(), bufferedimage.getHeight());
        } else
        {
            graphics2d.setComposite(AlphaComposite.getInstance(1, 0.0F));
            graphics2d.fillRect(0, 0, bufferedimage.getWidth(), bufferedimage.getHeight());
            graphics2d.setComposite(AlphaComposite.SrcOver);
        }
        graphics2d.translate((int)(-rectangle2d.getX() + (double)i), (int)(-rectangle2d.getY() + (double)i));
        boolean flag = jgraph.isDoubleBuffered();
        RepaintManager repaintmanager = RepaintManager.currentManager(jgraph);
        repaintmanager.setDoubleBufferingEnabled(false);
        jgraph.paint(graphics2d);
        repaintmanager.setDoubleBufferingEnabled(true);
        return bufferedimage;
    } else
    {
        return null;
    }
  }
  
  public static String[] toIDsAry(String[] userRecords){
    String[] IDs = new String[userRecords.length];
    for(int i=0;i<userRecords.length;i++){
      IDs[i]=userRecords[i].split("_")[0];
    }
    return IDs;
  }
  
}
